//
//  SelectImageView.m
//  Budejie
//
//  Created by 远成物流 on 2017/6/7.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "SelectImageView.h"
#import "SelectImageViewCell.h"
#import "ACAlertController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <TZImagePickerController/TZImagePickerController.h>
#import <TZImagePickerController/TZImageManager.h>

static NSString * const SelectImageViewCellID = @"SelectImageViewCell";
static NSInteger const cols = 4;
static NSInteger const space = 0;
static NSInteger const MaxImageCount = 9;

#define itemWH (ScreenW-(cols-1)*space)/cols

@interface SelectImageView ()<UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSMutableArray *selectedAssets;
}

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *imageArray;
//@property (strong, nonatomic) CLLocation *location;

@end

@implementation SelectImageView

-(NSArray *)imageArray{
    if (_imageArray == nil) {
        _imageArray = Alloc(NSMutableArray);
    }
    
    return _imageArray;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        _showAddButton = YES;
        selectedAssets = Alloc(NSMutableArray);
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(itemWH, itemWH);
        layout.minimumLineSpacing = space;
        layout.minimumInteritemSpacing = space;
        
        UICollectionView *collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.width_sd, itemWH) collectionViewLayout:layout];
        collect.backgroundColor = [UIColor whiteColor];
        collect.delegate = self;
        collect.dataSource = self;
        [self addSubview:collect];
        
        _collectionView = collect;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"SelectImageViewCell" bundle:nil] forCellWithReuseIdentifier:SelectImageViewCellID];
    }
    return self;
}

#pragma
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _showAddButton ? self.imageArray.count+1 : self.imageArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SelectImageViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SelectImageViewCellID forIndexPath:indexPath];
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteSelectImage:) forControlEvents:UIControlEventTouchUpInside];
    
    if (indexPath.row == self.imageArray.count) {
        cell.image.image = [UIImage imageNamed:@"addImageBtn"];
        cell.deleteBtn.hidden = YES;
    }else{
        cell.image.image = self.imageArray[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == self.imageArray.count && self.imageArray.count >= MaxImageCount) {
        
        [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"最多只能选择%ld张",(long)MaxImageCount]];
        
        return;
    }
    
    if (indexPath.row == self.imageArray.count){
        
        __weak typeof(self) weakSelf = self;
        
        ACAlertController *alert = [[ACAlertController alloc] initWithActionSheetTitles:@[@"相册", @"相机"] cancelTitle:@"取消"];
        [alert clickActionButton:^(NSInteger index) {
            if (index == 0) {
                [weakSelf openAlbum];
        }else {
                [weakSelf openCamera];
            }
        }];
        [alert show];
    }
}

/** 相册 */
-(void)openAlbum{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:MaxImageCount delegate:self];
    
    imagePickerVc.selectedAssets = selectedAssets; // 目前已经选中的图片数组
    
    // 2. Set the appearance
     imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
     imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets,BOOL isSelectOriginalPhoto) {
        
        self.imageArray = (NSMutableArray *)photos;
        selectedAssets = (NSMutableArray *)assets;
        
        //设置collectionview高度
        NSInteger rows = _showAddButton ? (photos.count)/cols+1 : (photos.count-1)/cols+1;
        self.collectionView.height_sd = rows * itemWH;
        self.height_sd = self.collectionView.height_sd;
        
        [self.collectionView reloadData];
        
        if (photos.count >= MaxImageCount) {
            _showAddButton = NO;
        }
    }];
    
    [_controller presentViewController:imagePickerVc animated:YES completion:nil];
}

/** 相机 */
- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [_controller presentViewController:picker animated:YES completion:nil];
    }else{
        [SVProgressHUD showWithStatus:@"该设备不支持拍照"];
    }
}

//删除按钮
-(void)deleteSelectImage:(UIButton *)sender{
    [self.imageArray removeObjectAtIndex:sender.tag];
    [selectedAssets removeObjectAtIndex:sender.tag];
    
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
        
        _showAddButton = YES;
    }];
}

//拍照完成后触发
- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    [selectedAssets addObject:asset];
    [self.imageArray addObject:image];
    [_collectionView reloadData];
    
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        NSLog(@"location:%@",phAsset.location);
    }
    
    if (self.imageArray.count >= MaxImageCount) {
        _showAddButton = NO;
    }
}

#pragma 
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = YES;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error) {
           
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        
                        // 允许裁剪,去裁剪
                        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                                [self refreshCollectionViewWithAddedAsset:asset image:cropImage];
                        }];
                        
                        //圆形显示
//                        imagePicker.needCircleCrop = YES;
//                        imagePicker.circleCropRadius = 100;
                        [_controller presentViewController:imagePicker animated:YES completion:nil];
                    }];
                }];
            }
            
        }];
    }
}

@end
